package com.dau.system.controller.system;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dau.common.annotation.CurrentUser;
import com.dau.common.constants.CommConstants;
import com.dau.common.result.R;
import com.dau.entity.system.user.LoginUser;
import com.dau.entity.system.user.SysUser;
import com.dau.service.system.user.SysUserService;
import com.dau.system.config.jwt.JwtUtils;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author tzj
 * @date 2024/11/15
 */
@RestController
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param loginUser 登录用户
     * @return {@link R }<{@link Map }<{@link String }, {@link Object }>>
     */
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginUser loginUser) {
        try {
            // 查询用户信息
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", loginUser.getUserName()));
            Assert.notNull(user, "用户不存在!");

            // 验证密码
            if (!BCrypt.checkpw(loginUser.getPassword(), user.getPassword())) {
                return R.error("用户名或密码不正确！");
            }

            // 生成JWT令牌
            String jwtToken = jwtUtils.generateToken(user.getId());

            // 构建返回结果
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("user", user);
            responseMap.put("token", jwtToken);

            return R.success(responseMap);
        } catch (Exception e) {
            // 记录日志
            logger.error("登录过程中发生错误: ", e);
            return R.error("登录错误，请稍后再试！");
        }

    }

    /**
     * 注销
     *
     * @return {@link R }<{@link ? }>
     */
    @GetMapping("/logout")
    public R<Boolean> logout() {
        SecurityUtils.getSubject().logout();
        return R.success(true);
    }

    /**
     * 刷新
     *
     * @param sysUser 系统用户
     * @return {@link R }<{@link Boolean }>
     */
    @GetMapping("/refresh")
    @RequiresPermissions("user:info:refresh")
    public R<Boolean> refresh(@CurrentUser SysUser sysUser) {
        this.redisTemplate.delete(CommConstants.AUTH_CACHE_KEY + sysUser.getId());
        return R.success(true);
    }
}
